const http = require('http')
const https = require('https')
const fs = require('fs')
const format = require('./formatApi')
const config = require('./config')

const url = config.url + config.path

function request(){
  let responseResult = ''
  return new Promise((resolve,reject) => {
    let req = (config.https?https:http).request(url,function(res){
      res.setEncoding('utf8');
      res.on('data', function (_chunk) {
        // 分片数据合并
        responseResult += _chunk;
      });
      res.on('end',()=>{
        resolve(responseResult);
      })
    })
    req.on('error', function (e) {
      console.log('error: ' + JSON.stringify(e));
      reject(JSON.stringify(e))
    });
    req.end();
  })
}


function main(){
   const folder = config.folder
   request().then(res => {
    const json =  JSON.parse(res)
     const {result:controller,useModel} = format.controllerFormat(json)
     const model = format.modelFormat(json.definitions,useModel)
     fs.mkdirSync(`${folder}`,{
       recursive:true
     })
     fs.writeFile(`${folder}/apidoc.ets`,
     model,
     function(){
       console.log('自定义类型写入成功,文件为apidoc.ets')
     })
     let exportStr = `import API from './api/apidoc'\n`;
    exportStr += `export {API}\n`;
     for (const i in controller) {
         exportStr += `export * from './api/${controller[i].name}' \n`
       fs.writeFile( `${folder}/${controller[i].name}.ets`,
       controller[i].context,
       function () {
         console.log(`模块${controller[i].name}写入成功`);
       })
     }
     fs.writeFile(`${folder.replace('/api','')}/exportApi.ets`,exportStr,()=>{
         console.log('导出模块写入成功')
     })
   })
}

main()


